package cn.edu.swu.miniwebsvr.core;

import cn.edu.swu.miniwebsvr.handler.DefaultHandler;
import java.io.OutputStream;

public class Router {

    public void route(Parameter request, OutputStream response) {
        Config config = Config.getInstance();

        // TODO: [2023123456/张三] 根据请求的URL获取Handler
        Handler handler = config.getHandler(request.getUrl());

        if (handler == null) {
            // 如果没有匹配的路由，使用 DefaultHandler 处理
            handler = config.getHandler("/");
        }

        if (handler != null) {
            handler.handle(request, response);
        } else {
            // TODO: [2023123456/张三] 如果连DefaultHandler都没有，返回500 Internal Server Error
            try {
                String errorContent = "<h1>500 Internal Server Error</h1><p>No handler configured for this server.</p>";
                response.write(("HTTP/1.1 500 Internal Server Error\r\n").getBytes());
                response.write(("Content-Type: text/html; charset=UTF-8\r\n").getBytes());
                response.write(("Content-Length: " + errorContent.getBytes().length + "\r\n").getBytes());
                response.write(("Connection: close\r\n").getBytes());
                response.write(("\r\n").getBytes());
                response.write(errorContent.getBytes());
                response.flush();
            } catch (Exception e) {
                System.err.println("Error sending 500 response: " + e.getMessage());
            }
        }
    }
}